package control;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.bean.usuario;

@WebFilter(filterName = "AuthenticationFilter", urlPatterns = "/*")
public class AuthenticationFilter implements Filter {
	
	private Map resources = new HashMap();

	protected String getNextURL(HttpServletRequest request) {
		String url = request.getRequestURI();
		StringBuffer params = new StringBuffer("");
		Enumeration enumParams = request.getParameterNames();

		while (enumParams.hasMoreElements()) {
			String name = (String) enumParams.nextElement();
			String value = request.getParameter(name);
			if (params.length() > 0) {
				params.append("&");
			}
			params.append(name).append("=").append(value);
		}
		return url + "?" + params.toString();
	}

	protected boolean verifyAccess(HttpServletRequest request) {
		String resource = request.getRequestURI().replaceAll(
				request.getContextPath(), "");
		
		while (resource.length() > 0) {
			String rules = (String) resources.get(resource);
			if (rules != null) {
				usuario user = (usuario) request.getSession().getAttribute("user");
				return (user != null &&  user.hasRules(rules));
			} else if (!resource.equals("/")) {
				int index = resource.lastIndexOf("/");
				if (index > -1) {
					resource = resource.substring(0, index);
				}
			} else {
				resource = "";
			}
		}
		return true;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		boolean allowed = verifyAccess((HttpServletRequest) request);
		if (!allowed) {
			String logon = "Index.jsp?next="
					+ getNextURL((HttpServletRequest) request);
			((HttpServletResponse) response).sendRedirect(logon);
		}
		chain.doFilter(request, response);

	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		try {
			String accessFile = this.getClass().getClassLoader()
					.getResource("access.properties").getPath();
			accessFile = accessFile.substring(1);
			Properties properties = new Properties();
			properties.load(new FileInputStream(accessFile));
			resources.putAll(properties);

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}
	}

}
